﻿using System.Reflection.PortableExecutable;
using System.Threading;
using System.Threading.Channels;
using TouchSocket.Core;
using TouchSocket.Modbus;
using TouchSocket.Sockets;

internal class Program
{
    private static async Task Main(string[] args)
    {
        var _modbusClient = new ModbusRtuOverTcpMaster();
        CancellationTokenSource _cts = new CancellationTokenSource();
        await _modbusClient.ConnectAsync("10.143.92.109:8234");
       
        Console.WriteLine($"连接状态Online：{_modbusClient.Online}");

        var aaa = Task.Run(() => SSS(_modbusClient, _cts.Token), _cts.Token);



        Console.ReadLine();
    }

    private static async Task SSS(ModbusRtuOverTcpMaster _modbusClient, CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            try
            {
                Random rd = new Random();
                var i = rd.Next(0, 9);
                var j = (ushort)i;
                Console.WriteLine($"随机一个地址：{i}");
                Console.WriteLine($"随机一个地址ushort：{j}");
                
                try
                {
                    var response = _modbusClient.ReadHoldingRegisters(1, j, 1);
                    Console.WriteLine($"response IsSuccess:{response.IsSuccess}");
                    Console.WriteLine($"response response.Data {string.Join("", response.Data.ToArray())}");
                    var result = response.CreateReader().ReadInt16(EndianType.Big);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    //var response = _modbusClient.ReadHoldingRegisters(1, j, 1);
                    //Console.WriteLine($"response IsSuccess:{response.IsSuccess}");
                    //Console.WriteLine($"response response.Data {string.Join("", response.Data.ToArray())}");
                    //var result = response.CreateReader().ReadInt16(EndianType.Big);
                    //Console.WriteLine($"地址{i}的值为：{result}");
                }
               
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            await Task.Delay(2000);
        }
    }
}